package icu.thatyear.transmission.controller;

import icu.thatyear.transmission.config.MinioConfig;
import icu.thatyear.transmission.pojo.FileInfo;
import icu.thatyear.transmission.pojo.Result;
import icu.thatyear.transmission.util.MinioUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

/**
 * Minio控制层
 */
@Log4j2
@CrossOrigin
@RestController
@RequestMapping("/minio")
public class MinioController {

    @Autowired
    private MinioUtils minioUtils;

    @Autowired
    private MinioConfig minioConfig;

    /**
     * 文件上传
     *
     * @param file
     */
    @PostMapping("/upload")
    public Result<String> upload(@RequestParam MultipartFile file) {
        try {
            //文件名
            String fileName = file.getOriginalFilename();
            //类型
            String contentType = file.getContentType();
            minioUtils.uploadFile(minioConfig.getBucketName(), file, fileName, contentType);

            return Result.success("上传成功");
        } catch (Exception e) {
            log.error("上传失败", e);
            return Result.err("上传失败");
        }
    }

    /**
     * 删除
     *
     * @param fileName
     */
    @DeleteMapping("/delete")
    public Result<String> delete(@RequestParam("fileName") String fileName) {
        try{
            minioUtils.removeFile(minioConfig.getBucketName(), fileName);
            return Result.success("删除成功");
        }catch (Exception e){
            return Result.err("删除失败");
        }

    }

    /**
     * 获取文件信息
     *
     * @param fileName
     * @return
     */
    @GetMapping("/info")
    public String getFileStatusInfo(@RequestParam("fileName") String fileName) {
        return minioUtils.getFileStatusInfo(minioConfig.getBucketName(), fileName);
    }

    /**
     * 获取文件外链
     *
     * @param fileName
     * @return
     */
    @GetMapping("/url")
    public String getPresignedObjectUrl(@RequestParam("fileName") String fileName) {
        String presignedObjectUrl = minioUtils.getPresignedObjectUrl(minioConfig.getBucketName(), fileName);
        return presignedObjectUrl;
    }

    /**
     * 文件下载
     *
     * @param fileName
     * @param response
     */
    @GetMapping("/download")
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        try {
            // 从 MinIO 获取指定的对象（文件）的输入流
            InputStream fileInputStream = minioUtils.getObject(minioConfig.getBucketName(), fileName);
            // 设置响应头，指明这是一个附件下载，并指定下载文件的名称
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            // 设置响应的内容类型为强制下载
            response.setContentType("application/force-download");
            // 设置响应的字符编码为 UTF-8
            response.setCharacterEncoding("UTF-8");
            // 将输入流中的文件内容复制到响应输出流中
            IOUtils.copy(fileInputStream, response.getOutputStream());
            response.flushBuffer(); // 刷新响应输出流
        } catch (Exception e) {
            log.error("下载失败");
            System.out.println(e);
        }
    }

    /**
     * 获取文件夹底下的文件列表
     * */
    @GetMapping("/folderList")
    public Result<List<FileInfo>> getFolderList(@RequestParam String folderName) {
        try{
            List<FileInfo> fileList = minioUtils.getFolderList("local-files",folderName);

            for (FileInfo fileInfo : fileList) {
                //文件包含/进行分割
                String[] fileNames = fileInfo.getName().split("/");
                String fileName = fileNames[fileNames.length - 1];
                fileInfo.setName(fileName);
            }

            return Result.success("获取文件列表成功", fileList);
        }catch (Exception e){
            return Result.err("获取文件列表失败");
        }
    }

    /**
     * 获取文件列表
     *
     * @return 文件列表
     */
    @GetMapping("/list")
    public Result<List<FileInfo>> getFileList() {
        List<FileInfo> fileList = minioUtils.getFileList("local-files");
        return Result.success("获取文件列表成功", fileList);

    }


}